<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/14
 * Time: 10:00
 */

namespace app\script\command;

use app\common\model\DataVideo;
use app\common\model\Job;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use PHPMailer\PHPMailer;

class Queue extends Base
{

    /**
     * 设置执行名称及配置传入参数、脚本描述
     */
    protected function configure()
    {
        $this->setName('queue')
            ->setDescription('Run all the time');
    }

    protected function execute(Input $input, Output $output)
    {
        exec("ps aux | grep 'php' | awk '{print $15}'", $res);
        $jobProcessArr = [];
        foreach ($res as $val) {
            $processId = [];
            $jobName = [];
            if (!empty($val) && strlen($val) > 10) {
                exec("ps aux | grep " . $val . " | awk '{print $2}'", $processId);
                exec("ps aux | grep " . $val . " | awk '{print $13}'", $jobName);
                $jobProcessArr[$val] = [
                    'processId' => $processId[0],
                    'command' => 'nohup php /var/www/html/crawl/think ' . $jobName[0] . ' --job ' . $val . ' >> /var/www/html/crawl/runtime/log/' . $val . '.log 2>&1 &',
                ];
            }
        }
        unset($res);
//            print_r($jobProcessArr);exit;
        $jobArr = $this->redis->hGetAll('job_status');
        $jobModel = new Job();
//            $jobMsg = [];
        foreach ($jobArr as $key => $value) {
            if ($value == 1 && time() - filectime(LOG_PATH . $key . '.log') > 60) {
                $this->redis->hSet('job_status', $key, -1);
                $jobModel->isUpdate(true)->save(['job_status' => -1, 'status_time' => date('Y-m-d H:i:s')],
                    ['id' => $key]);
//                    array_push($jobMsg,$key);
            } elseif ($value == -1 && array_key_exists($key, $jobProcessArr)) {
                $this->redis->hSet('job_status', $key, 1);
                $jobModel->isUpdate(true)->save(['job_status' => 1, 'status_time' => date('Y-m-d H:i:s')],
                    ['id' => $key]);
                exec("kill -9 " . $jobProcessArr[$key]['processId']);
                exec($jobProcessArr[$key]['command']);
            } elseif ($value == -1 && !array_key_exists($key, $jobProcessArr)) {
                $this->redis->hSet('job_status', $key, 1);
                $jobInfo = $jobModel->field('script_name')->where(['id' => $key])->find();
                $jobModel->isUpdate(true)->save(['job_status' => 1, 'status_time' => date('Y-m-d H:i:s')],
                    ['id' => $key]);
                exec('nohup php /var/www/html/crawl/think ' . $jobInfo['script_name'] . ' --job ' . $key . ' >> /var/www/html/crawl/runtime/log/' . $key . '.log 2>&1 &');
            }
        }
        unset($jobModel);
        unset($jobProcessArr);
        unset($jobArr);
//            if(!empty($jobMsg)){
////                $this->SendEmail('系统提醒','采集脚本异常关闭任务ID【'.implode(',',$jobMsg).'】');
//            }
//            unset($jobMsg);
    }

    public function SendEmail($title = '', $message = '', $emailAddress = 'zhenghebin1988@163.com')
    {
        $mailArr = config('mail');
        $mail = new PHPMailer();
        //3.设置属性，告诉我们的服务器，谁跟谁发送邮件
        $mail->IsSMTP();            //告诉服务器使用smtp协议发送
        $mail->SMTPAuth = true;        //开启SMTP授权
        $mail->Host = 'smtp.163.com';    //告诉我们的服务器使用163的smtp服务器发送
        $mail->From = $mailArr['username'];    //发送者的邮件地址
        $mail->Username = $mailArr['username'];    //登录到邮箱的用户名
        $mail->Password = $mailArr['password'];        //第三方登录的授权码，在邮箱里面设置
        //编辑发送的邮件内容
        $mail->IsHTML(true);            //发送的内容使用html编写
        $mail->CharSet = 'utf-8';        //设置发送内容的编码
        $mail->Subject = $title;//设置邮件的标题
        $mail->MsgHTML($message);    //发送的邮件内容主体
        $mail->AddAddress($emailAddress);    //收人的邮件地址
        //调用send方法，执行发送
        $result = $mail->Send();
        if ($result) {
            return true;
        } else {
            return $mail->ErrorInfo;
        }
    }
}